package com.gc.web.controller.business;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import com.gc.business.domain.InventoryInfo;
import com.gc.business.domain.InventoryRecord;
import com.gc.business.domain.PartApplication;
import com.gc.business.service.IInventoryInfoService;
import com.gc.business.service.IInventoryRecordService;
import com.gc.business.service.IPartApplicationService;
import com.gc.common.annotation.Log;
import com.gc.common.base.Result;
import com.gc.common.constant.Constants;
import com.gc.common.enums.BusinessType;
import com.gc.common.support.Convert;
import com.gc.common.utils.poi.ExcelUtil;
import com.gc.framework.util.ShiroUtils;
import com.gc.framework.web.base.BaseController;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 出入库记录 控制层
 * 
 * @author hruiyan
 * @date 2020-11-10
 */
@Slf4j
@Controller
@RequestMapping("/business/inventoryRecord")
public class InventoryRecordController extends BaseController {
    private String prefix = "business/inventoryRecord";

	@Autowired
	private ISysUserService sysUserService;
	
	private final IInventoryRecordService inventoryRecordService;

	private final IInventoryInfoService inventoryInfoService;

	private final IPartApplicationService partApplicationService;

	@Autowired
	public InventoryRecordController(IInventoryRecordService inventoryRecordService,
									 IInventoryInfoService inventoryInfoService,
									 IPartApplicationService partApplicationService) {
		this.inventoryRecordService = inventoryRecordService;
		this.inventoryInfoService = inventoryInfoService;
		this.partApplicationService = partApplicationService;
	}

	/**
	*  列表页
	*/
	@RequiresPermissions("business:inventoryRecord:view")
	@GetMapping("/{recordType}")
	public String inventoryRecord(@PathVariable("recordType")Integer recordType,ModelMap mmap){
		mmap.put("recordType",recordType);
		if(1 == recordType){
			return prefix + "/putStorage";
		}else if(2 == recordType){
			return prefix + "/outBound";
		}
		return "error/404";
	}

	/**
	 * 新增页
	 */
	@GetMapping("/add")
	public String add(){
		return prefix + "/add";
	}

	/**
	 * 编辑页
	 */
	@GetMapping("/edit/{recordId}")
	public String edit(@PathVariable("recordId") Long recordId, ModelMap mmap){
		InventoryRecord inventoryRecord = inventoryRecordService.getById(recordId);
		mmap.put("inventoryRecord", inventoryRecord);
		return prefix + "/edit";
	}
	
	/**
	 * 查询出入库记录列表
	 */
	@RequiresPermissions("business:inventoryRecord:list")
	@PostMapping("/list")
	@ResponseBody
	public Result list(InventoryRecord inventoryRecord){
		//查询该用户归属的公司下有哪些库存(库存与公司关联)
		if(sysUserService.ifCompanyRole(getAttrId())){
			InventoryInfo inventoryInfo = new InventoryInfo().setAttrId(getAttrId());
			List<InventoryInfo> infoList = inventoryInfoService.list(inventoryInfo);
			if (CollUtil.isEmpty(infoList) || infoList.size() == 0){
				return Result.success();
			}
			List<Long> collect = infoList.stream().map(InventoryInfo::getInventoryId).collect(Collectors.toList());
			startPage();
			List<InventoryRecord> list = inventoryRecordService.list(inventoryRecord,collect);
			return Result.success(getDataTable(list));
		}else {
			return Result.success(getDataTable(new ArrayList<InventoryRecord>()));
		}
	}

	/**
	 * 新增保存出入库记录
	 */
	@RequiresPermissions("business:inventoryRecord:add")
	@Log(title = "出入库记录", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(InventoryRecord inventoryRecord){
		inventoryRecordService.save(inventoryRecord);
		return Result.success();
	}

	/**
	 * 修改保存出入库记录
	 */
	@RequiresPermissions("business:inventoryRecord:edit")
	@Log(title = "出入库记录", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(InventoryRecord inventoryRecord){
		inventoryRecordService.updateById(inventoryRecord);
		return Result.success();
	}
	
	/**
	 * 删除出入库记录
	 */
	@RequiresPermissions("business:inventoryRecord:remove")
	@Log(title = "出入库记录", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public Result remove(String ids){
		Long[] longIds = Convert.toLongArray(ids);
		inventoryRecordService.removeByIds(Arrays.asList(longIds));
		return Result.success();
	}

	/**
	 * 导出出入库记录列表
	 */
	@RequiresPermissions("business:inventoryRecord:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(InventoryRecord inventoryRecord){
		List<InventoryRecord> list = new ArrayList<>();
		if(sysUserService.ifCompanyRole(getAttrId())){
			InventoryInfo inventoryInfo = new InventoryInfo().setAttrId(getAttrId());
			List<InventoryInfo> infoList = inventoryInfoService.list(inventoryInfo);
			if (CollUtil.isEmpty(infoList) || infoList.size() == 0){
				return Result.success();
			}
			List<Long> collect = infoList.stream().map(InventoryInfo::getInventoryId).collect(Collectors.toList());
			list = inventoryRecordService.list(inventoryRecord,collect);
		}
		ExcelUtil<InventoryRecord> util = new ExcelUtil<>(InventoryRecord.class);
		util.exportExcel(list, "inventoryRecord");
		return Result.success();
	}

	/**
	 * 出库审核通过
	 */
	@GetMapping("/outBoundPass/{recordId}")
	public String outBoundPass(@PathVariable("recordId") Long recordId, ModelMap mmap){
		PartApplication partApplication = partApplicationService.getById(recordId);
		mmap.put("receivePeople",partApplication.getReceivePeople());
		mmap.put("partName",partApplication.getPartName());
		mmap.put("partApplication", partApplication);
		return prefix + "/outBoundPass";
	}

	/**
	 * 出库审核通过
	 */
	@PostMapping("/outBoundAuditPass")
	@ResponseBody
	public Result outBoundAuditPass(Long partId,String auditStatus){
		Console.log("partId:{},auditStatus:{}",partId,auditStatus);
		PartApplication partApplication = partApplicationService.getById(partId);
		if (!partApplication.getAuditStatus().equals("0")){
			return Result.failed("配件申请已审核");
		}
		String result = partApplicationService.executeMethod(partApplication, auditStatus, null);
		if (result.equals("0")){
			return Result.success();
		}
		return Result.failed("审核失败");
	}

	/**
	 * 出库审核拒绝
	 */
	@GetMapping("/outBoundRefuse/{recordId}")
	public String outBoundRefuse(@PathVariable("recordId") Long recordId, ModelMap mmap){
		PartApplication partApplication = partApplicationService.getById(recordId);
		mmap.put("partApplication", partApplication);
		return prefix + "/outBoundRefuse";
	}

	/**
	 * 出库审核拒绝
	 */
	@PostMapping("/outBoundAuditRefuse")
	@ResponseBody
	public Result outBoundAuditRefuse(Long partId,String auditStatus,String refuseReason){
		Console.log("partId:{},auditStatus:{},refuseReason:{}",partId,auditStatus,refuseReason);
		PartApplication partApplication = partApplicationService.getById(partId);
		if (!partApplication.getAuditStatus().equals("0")){
			return Result.failed("配件申请已审核");
		}
		String result = partApplicationService.executeMethod(partApplication, auditStatus, refuseReason);
		if (result.equals("1")){
			return Result.failed( "暂无该配件");
		}else if (result.equals("2")){
			return Result.failed( "本配件暂无该规格数据");
		}else if (result.equals("3")){
			return Result.failed("配件数量不足");
		}
		partApplication.setAuditStatus(auditStatus);
		Long userId = ShiroUtils.getUserId();
		partApplication.setApproveId(userId);
		if (partApplicationService.updateById(partApplication)){
			InventoryRecord inventoryRecord = inventoryRecordService.getById(partApplication.getRecordId());
			SysUser user = sysUserService.selectUserById(userId);
			inventoryRecord.setAuditor(user.getUserName());
			inventoryRecord.setAuditStatus(auditStatus);
			if (auditStatus.equals("2")){
				partApplication.setRejectCause(refuseReason);
			}
			inventoryRecordService.updateById(inventoryRecord);
			return Result.success("审核完成");
		}
		return Result.failed("审核失败");
	}

	/**
	 * 出库拒绝原因
	 */
	@RequiresPermissions("business:inventoryRecord:detail")
	@GetMapping("/outBoundRefuseReason/{recordId}")
	public String outBoundRefuseReason(@PathVariable("recordId") Long recordId, ModelMap mmap){
		PartApplication partApplication = partApplicationService.getById(recordId);
		mmap.put("partApplication", partApplication);
		return prefix + "/outBoundRefuseReason";
	}

	/**
	 * 出库记录详情
	 */
	@RequiresPermissions("business:inventoryRecord:detail")
	@GetMapping("/passDetail/{recordId}")
	public String passDetail(@PathVariable("recordId") Long recordId, ModelMap mmap){
		PartApplication partApplication = partApplicationService.getById(recordId);
		if (partApplication.getAuditStatus().equals("0")){
			partApplication.setAuditStatus("待审核");
		}else if (partApplication.getAuditStatus().equals("1")){
			partApplication.setAuditStatus("通过");
		}else if (partApplication.getAuditStatus().equals("2")){
			partApplication.setAuditStatus("拒绝");
		}
		mmap.put("partApplication", partApplication);
		return prefix + "/edit";
	}
}
